package cn.itsub.proxy.client.ui;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MainFrame {

    private JFrame frame;
    private JTextField serverAddressField;
    private JTextField clientEncodingField;
    private TrayIcon trayIcon;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MainFrame example = new MainFrame();
            example.createAndShowGUI();
        });
    }

    private void createAndShowGUI() {
        // 创建主界面
        frame = new JFrame("界面程序");
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);

        // 创建输入框
        serverAddressField = new JTextField();
        clientEncodingField = new JTextField();

        // 创建布局
        JPanel panel = new JPanel(new GridLayout(2, 2));
        panel.add(new JLabel("服务器地址:"));
        panel.add(serverAddressField);
        panel.add(new JLabel("客户端编码:"));
        panel.add(clientEncodingField);

        // 添加布局到主界面
        frame.getContentPane().add(panel, BorderLayout.CENTER);

        // 创建托盘图标
        if (SystemTray.isSupported()) {
            SystemTray tray = SystemTray.getSystemTray();
            Image image = Toolkit.getDefaultToolkit().getImage("icon.png"); // 替换为你的图标路径
            ActionListener showAction = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    frame.setVisible(true);
                    frame.setExtendedState(JFrame.NORMAL);
                }
            };
            ActionListener exitAction = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            };
            PopupMenu popupMenu = new PopupMenu();
            MenuItem showItem = new MenuItem("显示");
            showItem.addActionListener(showAction);
            MenuItem exitItem = new MenuItem("退出");
            exitItem.addActionListener(exitAction);
            popupMenu.add(showItem);
            popupMenu.add(exitItem);
            trayIcon = new TrayIcon(image, "程序名称", popupMenu);
            trayIcon.addActionListener(showAction);
            try {
                tray.add(trayIcon);
            } catch (AWTException e) {
                e.printStackTrace();
            }
        }

        // 添加窗口关闭事件
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                frame.setVisible(false);
            }
        });

        // 显示主界面
        frame.setVisible(true);
    }
}